package com.xxx.control.base

import android.os.Bundle
import android.text.TextUtils
import android.view.WindowManager
import androidx.lifecycle.ViewModelProvider
import androidx.viewbinding.ViewBinding
import com.xxx.control.net.NetWorkException
import com.dylanc.viewbinding.inflateBindingWithGeneric
import com.gyf.immersionbar.ImmersionBar
import com.xxx.control.R
import retrofit2.HttpException
import java.io.IOException

abstract class BaseVMActivity<V : ViewBinding, VM : BaseViewModel> :
    BaseActivity() {

    lateinit var mBinding: V

    protected lateinit var mViewModel: VM


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN)

        mBinding = inflateBindingWithGeneric(layoutInflater)
        setContentView(mBinding.root)

        initViewModel()

        ImmersionBar.with(this)
            .statusBarColor(R.color.color_003e83)
            .statusBarDarkFont(false)
            .navigationBarColor(R.color.black)
            .fitsSystemWindows(true).init()

    }

    /**
     * 初始化ViewModel
     */
    private fun initViewModel() {
        val viewModelClass: Class<VM>? = ClassUtil.getViewModel(this)
        if (viewModelClass != null) {
            mViewModel = ViewModelProvider(this)[viewModelClass]
        }
    }

    fun showException(e: Throwable) {
        var code = 0
        var errorMsg = e.message
        if (e is Exception) {
            if (e is IOException) {
                /** 没有网络  */
                errorMsg = "Please check your network status"
            } else if (e is HttpException) {
                /** 网络异常，http 请求失败，即 http 状态码不在 [200, 300) 之间, such as: "server internal error".  */
//            errorMsg = ((HttpException) e).response().message();
                e.response()?.apply {
                    code = code()
                    if (errorBody() != null) {
                        errorMsg = errorBody()!!.string()
                    }
                }


            } else if (e is NetWorkException) {
                code = e.code
                errorMsg = e.message
            } else {
                /** 其他未知错误  */
                errorMsg = if (!TextUtils.isEmpty(e.message)) e.message else "unknown error"
            }
            if (errorMsg == "") {
                errorMsg = e.message
            }
            toast(errorMsg)
//            loadFailure(code, errorMsg!!)
            e.printStackTrace()
        }
    }

    override fun finish() {
        hideSoftKeyboard()
        super.finish()
    }

}